<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<%@ taglib prefix='c' uri='http://java.sun.com/jsp/jstl/core' %>
<%@ taglib prefix='fn' uri='http://java.sun.com/jsp/jstl/functions' %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%
    /**
     * @Description :  General Board form
     * @Modification Information
     *
     *   수정일               수정자                   수정내용
     *  -------    --------    ---------------------------
     *
     *
     */
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />    
<title><tiles:insertAttribute name="headtitle" ignore="true"/></title>

<link rel="stylesheet" type="text/css" media="screen" href="<c:url value='/resources/css/jquery/start/jquery-ui-1.10.3.custom.css'/>" />
<link rel="stylesheet" type="text/css" media="all"  href="<c:url value='/resources/css/kickstart/kickstart.css'/>"/> <!-- KICKSTART -->

<script type="text/javascript" src="<c:url value='/resources/js/jquery/jquery-1.9.0.min.js'/>"></script>
<script type="text/javascript" src="<c:url value='/resources/js/jquery/jquery-ui-1.10.3.custom.min.js'/>"></script>
<script type="text/javascript" src="<c:url value='/resources/js/kickstart/kickstart.js'/>"></script> <!-- KICKSTART -->
<%@include file="/WEB-INF/jsp/common/commonJs.jsp"%> 

<!-- additional -->
<script type="text/javascript" src="<c:url value='/resources/js/jquery/plugin/form/jquery.form.min.js'/>"></script>
<script type="text/javascript" src="<c:url value='/resources/js/jquery/plugin/validate/jquery.validate.min.js'/>"></script>
<!-- //additional -->

<script type="text/javascript">
$(document).ready(function() {
	
//********************************************************
// event handler area   
//********************************************************  
    //////////////////////////
    // 저장처리
    $("#btnRegist").click(function() { // 글등록
        event.preventDefault();
        
        if(confirm("글을 등록하시겠습니까??")) {
            $("#form1").prop("action",'<c:url value="/bbs/bbsGeneralBoard/regist"/>?bbs_id=${params.bbs_id}');
            $("#action_name").val("REGIST");
            $("#form1").submit();
        }    
    }); 
    $("#btnUpdate").click(function() { // 글수정
        event.preventDefault();
        
        if(confirm("글을 수정하시겠습니까??")) {
            $("#form1").prop("action",'<c:url value="/bbs/bbsGeneralBoard/update"/>?bbs_id=${params.bbs_id}');
            $("#action_name").val("UPDATE");
            $("#form1").submit();
        }    
    }); 
    $("#btnDelete").click(function() {
        event.preventDefault();
        
        if(confirm("글을 삭제하시겠습니까??")) {
            $("#form1").prop("action",'<c:url value="/bbs/bbsGeneralBoard/delete"/>?bbs_id=${params.bbs_id}');
            $("#action_name").val("DELETE");
            $("#form1").submit();
        }
    }); 
    $("#btnReply").click(function() { // 글답변 등록
        event.preventDefault();
        
        if(confirm("답변글을 등록하시겠습니까??")) {
            $("#form1").prop("action",'<c:url value="/bbs/bbsGeneralBoard/reply"/>?bbs_id=${params.bbs_id}');
            $("#action_name").val("REPLY");
            $("#form1").submit();
        }
    }); 
    $("#btnComment").click(function() { // 댓글 등록
        event.preventDefault();
        
//!!!! submit이벤트 아닌 경우 validate 발생
        if(!$("#formComment").valid()) return false;
    
        if(confirm("댓글을 등록하시겠습니까??")) {
            var params = {
                atcl_id: '${params.atcl_id}',
                writer_id: $("#writer_id").val(),
                writer_nm: $("#writer_nm").val(),
                contents: $("#cmmt_contents").val(),
            };
            $("#divComment").load('<c:url value="/bbs/bbsGeneralBoard/registComment"/>?bbs_id=${params.bbs_id}', params, function(response, status, xhr) {
                if(status == 'error') {
                    viewError(response); 
                    return false;
                }
            });
        }
    }); 
    $("#btnReplyComment").click(function() { // 답댓글 등록
        event.preventDefault();
        
//!!!! submit이벤트 아닌 경우 validate 발생    
        if(!$("#formComment").valid()) return false;
    
        if(confirm("답댓글을 등록하시겠습니까??")) {
            Comment.atcl_id = '${params.atcl_id}';
            Comment.writer_id = $("#writer_id").val();
            Comment.writer_nm = $("#writer_nm").val();
            Comment.contents = $("#cmmt_contents").val();
            
            $("#divComment").load('<c:url value="/bbs/bbsGeneralBoard/replyComment"/>?bbs_id=${params.bbs_id}', Comment, function(response, status, xhr) {
                if(status == 'error') {
                    viewError(response); 
                    return false;
                }
            });
        }
    });    
    
    //////////////////////////
    // 폼이동
    $("#btnList").click(function() { // 목록
        event.preventDefault();
        /////////////////////////////////////////////////////
        // validate rules 비활성화
        $("#form1").validate().currentForm = '';
        /////////////////////////////////////////////////////

        $("#form1").prop("action",'<c:url value="/bbs/bbsGeneralBoard/list"/>?bbs_id=${params.bbs_id}');
        $("#action_name").val("LIST");
        $("#form1").submit();       
    });     
    $("#btnUpdateForm").click(function() { // 수정폼
        event.preventDefault();
        $("#form1").prop("action",'<c:url value="/bbs/bbsGeneralBoard/form"/>?bbs_id=${params.bbs_id}');
        $("#action_name").val("UPDATE_FORM");
        $("#form1").submit();
    });     
    $("#btnReplyForm").click(function() { // 답글폼
        event.preventDefault();
        $("#form1").prop("action",'<c:url value="/bbs/bbsGeneralBoard/form"/>?bbs_id=${params.bbs_id}');
        $("#action_name").val("REPLY_FORM");
        $("#form1").submit();
    });     
    
    //////////////////////////
    // 폼요소 핸들링
    $("#btnAttachAdd").click(function() { // 파일추가
        $('#tblAttach').append(
                '<tr>'+ 
                '    <td width="10%"></td>' + 
                '    <td width="30%" class="left"><input type="file" id="attachFile[]" name="attachFile[]" /></td>'+
                '    <td width="60%" class="left"><button id="btnAttachDel[]" name="btnAttachDel[]"  type="button"  class="attachDel">-</button></td>' + 
                '</tr>');
        $(".attachDel").on('click', function() {
            $(this).parent().parent().remove();
        });        
        
    });
    $(".attachDel").on('click', function() {
        $(this).parent().parent().remove();
    });

//********************************************************
// Validate define area   
//********************************************************  
    $("#form1").validate({
        rules: {},
        messages:{},
        //submitHandler: Form1.registForm,
        showErrors:function(errorMap, errorList){
            this.defaultShowErrors();
        },
        invalidHandler: function(event, validator) {
            var errors = validator.numberOfInvalids();
            if (errors) {
              var message = errors == 1
                ? 'You missed 1 field. It has been highlighted'
                : 'You missed ' + errors + ' fields. They have been highlighted';
              alert(validator.errorList[0].message);
            }
        } ,
    });      
    
	// 페이지초기화
    initPage();
});
   

//********************************************************
// page init/finalize area   
//********************************************************
var vRules; // ValidateRules object


/**
 * initialize page 
 */ 
var initPage = function() {
//***********************************************
// validation rules setup
//***********************************************
    vRules = new ValidateRules();
    vRules.addRules("#mem_id", "작성자ID");
    vRules.addRules("#mem_name", "작성자명");
    vRules.addRules("#email_id", "이메일주소");    
    vRules.addRules("#subject", "제목");    
    vRules.addRules("#contents", "내용");    
    // date from~to 비교
    vRules.addRules("#view_stdt, #view_eddt", "게시기간",{
        required: true,
        compareDate: {fromDate:"#view_stdt", toDate:"#view_eddt"},
        messages: {
            required: formatStr("{0}은(는) 필수입력입니다.","게시판 사용기간"),
            compareDate: formatStr("{0}은(는) 시작일자가 종료일자보다 클수 없습니다.","게시판 사용기간"),
        }
    });
    
//***********************************************
// 폼컨트롤 setup
//***********************************************
    // calendar 
    $( "#view_stdt, #view_eddt" ).datepicker({
        dateFormat: 'yy/mm/dd',
        showOn: "button",
        buttonImage: "<c:url value='/resources/images/calendar_blue.png'/>",
        buttonImageOnly: true,
        changeMonth: true, // 월선택 select box 표시 (기본은 false)
        changeYear: true,  // 년선택 selectbox 표시 (기본은 false)
        showButtonPanel: true, // 하단 today, done  버튼기능 추가 표시 (기본은 false) 
    });    
    var view_stdt = yyyymmdd('${item.VIEW_STDT}');
    var view_eddt = '${item.VIEW_EDDT}'=='' ? '9999/12/31':yyyymmdd('${item.VIEW_EDDT}');    
    $("#view_stdt").val(view_stdt);
    $("#view_eddt").val(view_eddt);   
};

/**
 * finalize page 
 */ 
var finalizePage = function() {
}; 


//********************************************************
// form validation area   
//********************************************************  
$.validator.setDefaults({
    debug: false,
    ignore: [], // hidden 필드 체크하기 위한 옵션
}); 

//********************************************************
//form process area   
//******************************************************** 
var deleteComment = function(cmmtId) { // 댓글삭제
    if(confirm("댓글을 삭제하시겠습니까??")) {
        var params = {
            atcl_id: '${params.atcl_id}',
            cmmt_id: cmmtId,
        };
        $("#divComment").load('<c:url value="/bbs/bbsGeneralBoard/deleteComment"/>?bbs_id=${params.bbs_id}', params, function(response, status, xhr) {
            if(status == 'error') {
                viewError(response); 
                return false;
            }
        });
    }	
};

// 댓글에 답변다는 경우 넘기는 파라미터
var Comment = {
    cmmt_id:'',
    thread:'',
    depth:'',
    order_seq:'',
};
var replyCommentMark = function(cmmtId) { // 댓글에 답변달기
	Comment.cmmt_id = $("#divCmmtId-"+cmmtId).text();
	Comment.thread = $("#divThread-"+cmmtId).text();
	Comment.depth = $("#divDepth-"+cmmtId).text();
	Comment.order_seq = $("#divOrderSeq-"+cmmtId).text();
	
	var contents = $("#divContents-"+cmmtId).text();
	$("#divCmmtReplyDesc").html('<br><font color=red>"</font><b>'+contents.substring(0, 50) + '</b><font color=red>"</font>... 글의 답변을 답니다.');
	
};
</script>
</head>
<body>
*Params:<br>
  ${params}<br>
*Item:<br>
  ${item}<br>
*Comment:<br>
  ${listCmmt}<br>
*Attach:<br>
  ${listAtch}
  
<!-- 사용자id/명 세팅 -->
<c:choose>
    <c:when test="${params.action_name=='NEW_FORM' }">
        <c:set var="mem_id" value="${sessionScope.userInfo.userId}"/>
        <c:set var="mem_name" value="${sessionScope.userInfo.userName}"/>
    </c:when>
    <c:otherwise>
        <c:set var="mem_id" value="${item.MEM_ID}"/>
        <c:set var="mem_name" value="${item.MEM_NAME}"/>
    </c:otherwise>
</c:choose>
<!-- //사용자id/명 세팅 -->  
  
<form id="form1" name="form1" method="post" enctype="multipart/form-data">
    <h3>
       <c:choose>
           <c:when test="${params.action_name=='NEW_FORM'}">글등록</c:when>
           <c:when test="${params.action_name=='DETAIL_FORM'}">글보기</c:when>
           <c:when test="${params.action_name=='UPDATE_FORM'}">글수정</c:when>
           <c:when test="${params.action_name=='REPLY_FORM'}">글답변</c:when>
           <c:otherwise>상세</c:otherwise>
       </c:choose> 
    </h3>
    <table width="100%" border="0" cellpadding="0" cellspacing="1" summary="게시판명,게시판 소개,게시판 유형,게시판 속성,답장가능여부, ..   입니다">
        <colgroup>
            <col width="14%"/>
            <col width="16%"/>
            <col width="20%"/>
            <col width="14%"/>
            <col width="16%"/>
            <col width="20%"/>
        </colgroup>
        <tbody>
            <tr>
                <td>
                    <label for="mem_id">작성자ID</label>
                </td>
                <td colspan="2">
                    <input id="mem_id" name="mem_id" type="text" readonly="readonly" value="${mem_id}"/>
                </td>
                <td>
                    <label for="mem_name">작성자명</label>
                </td>
                <td colspan="2">
                    <input id="mem_name" name="mem_name" type="text" readonly="readonly" value="${mem_name}"/>
                </td>
            </tr>    
            <tr>
                <td>
                    <label for="email_id">이메일주소</label>
                </td>
                <td colspan="5">
                    <input id="email_id" name="email_id" type="text" value="${item.EMAIL_ID}"/>
                </td>
            </tr>    
            <tr>
                <td>
                    <label for="subject">제목</label>
                </td>
                <td colspan="5">
                    <c:if test="${params.action_name=='REPLY_FORM'}">
                        <c:set var="re" value="RE:"/>
                    </c:if>
                    <c:if test="${params.action_name!='REPLY_FORM'}">
                        <c:set var="re" value=""/>
                    </c:if>
                    <input id="subject" name="subject" type="text" value="${re}${item.SUBJECT}" style="width:400px;"/>
                </td>
            </tr>    
            <tr>
                <td>
                    <label for="contents">내용</label>
                </td>
                <td colspan="5">
                    <textarea id="contents" name="contents" placeholder="" style="width:50%;height:100px;" ><c:out value="${item.CONTENTS}" escapeXml="true" /></textarea>
                </td>
            </tr>
            <c:if test="${params.action_name=='NEW_FORM'}">   
            <tr>
                <td>
                    <label for="contents">태그</label>
                </td>
                <td colspan="5">
                    <input id="tag_id" name="tag_id" type="text" value="" style="width:400px;"/>&nbsp;쉽표(,)구분으로 한번에 여러 태그를 입력할수 있습니다
                </td>
            </tr>
            </c:if> 
            <tr>
                <td>
                    <label for="contents">첨부파일</label>
                </td>
                <td colspan="5">
                    <c:if test="${params.action_name != 'DETAIL_FORM'}"><!-- 상세폼이 아닌 경우 추가버튼 추가 -->
                    <button id="btnAttachAdd" name="btnAttachAdd" type="button" >+</button>
                    </c:if>    
                    <table id="tblAttach"> 
                       <!--<tr>
                           <td width="50%" class="left"><input type="file" id="attachFile[]" name="attachFile[]"/></td>
                           <td width="50%" class="left"><button id="btnAttachDel[]" name="btnAttachDel[]" type="button" class="attachDel">삭제</button></td>
                       </tr>  -->
                       
                       <!-- ////////////////////////////// -->
                        <!-- 첨부파일 -->
                        <c:forEach var="row" items="${listAtch}" varStatus="status">
                        <tr>
                            <td width="10%">${status.count}</td>
                            <td width="30%" class="left"><c:out value="${row.ATCH_FILE_NM}"/>&nbsp;<c:out value="${row.ATCH_FILE_SIZE}"/>&nbsp;Bytes</td>
                            <td width="60%" class="left">
                                <c:if test="${params.action_name != 'DETAIL_FORM'}"><!-- 상세보기가 아닌경우 -->
                                    <input type="checkbox" id="chkAttachDel[]" name="chkAttachDel[]" value="${row.ATCH_ID}">삭제
                                </c:if>
                                <input type="hidden" id="atchIds[]" name="atchIds[]" value="${row.ATCH_ID}"><!-- 게시글 삭제시 파일삭제를 위해 사용 -->
                            </td>
                        </tr>
                        </c:forEach>
                        <!-- //첨부파일 -->
                       <!-- ////////////////////////////// -->    
                    </table>    
                </td>
            </tr>    
            <tr>
                <td>
                    <label for="">게시기간</label>
                </td>
                <td colspan="5">
                    <input id="view_stdt" name="view_stdt" type="text" readonly="readonly"  value=""/> ~ 
                    <input id="view_eddt" name="view_eddt" type="text" readonly="readonly"  value=""/>
                </td>
            </tr>             
        </tbody>
    </table>
    <!-- 페이징처리를 위하여 항상 따라다니는 값 -->
    <input type="hidden" id="bbs_id" name="bbs_id" value="${params.bbs_id}"/>
    <input type="hidden" id="page_no" name="page_no" value="${params.page_no}"/>
    <input type="hidden" id="action_name" name="action_name" value="${params.action_name}"/>
    <input type="hidden" id="atcl_id" name="atcl_id" value="${params.atcl_id}"/><!-- 글번호 -->
    <input type="hidden" id="thread" name="thread" value="${item.THREAD}"/><!--Thread(글그룹) -->
    <input type="hidden" id="depth" name="depth" value="${item.DEPTH}"/><!--depth(들여쓰기) -->
    <input type="hidden" id="order_seq" name="order_seq" value="${item.ORDER_SEQ}"/><!--소트번호 -->
    <!-- //페이징처리를 위하여 항상 따라다니는 값 -->
</form>

<!-- 
댓글 폼 
  : 상세폼인 경우 댓글목록/댓글등록폼 출력      
-->
<c:if test="${params.action_name == 'DETAIL_FORM'}">    
<hr/>
<div id="divComment">
    <%@include file="bbsGeneralBoardFormComment.jsp"%>
</div> 
</c:if>    
<!-- //댓글 폼 -->

<hr>

<div class="col_12 center">
    <button id="btnRegist">등록</button><!-- 0depth글 등록 -->
    <button id="btnUpdate">수정</button><!-- 글수정(수정폼>수정버튼) -->
    <button id="btnDelete">삭제</button>
    &nbsp;&nbsp;
    <button id="btnList" class="cancel">목록</button>
    &nbsp;&nbsp;
    <button id="btnUpdateForm">수정폼</button><!-- 수정폼 이동 -->
    <button id="btnReplyForm">답글폼</button><!-- 답글폼 이동 -->
    <button id="btnReply">답글등록</button><!-- ndepth답글 등록(답글폼>답글등록버튼) -->
    &nbsp;&nbsp;
    <button id="btnComment">댓글등록</button><!-- 댓글 등록 -->
    <button id="btnReplyComment">답댓글등록</button><!-- 답댓글 등록 -->
</div>

</body>
</html>